import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UploadPictures } from './upload-pictures.entity';

@Injectable()
export class UploadPicturesService {
  constructor(
    @InjectRepository(UploadPictures)
    private uploadPicturesRepository: Repository<UploadPictures>,
  ) {}

  async create(createUploadPicturesDto: any): Promise<UploadPictures> {
    console.log('=== UploadPicturesService.create 调试 ===');
    console.log('接收到的 DTO:', createUploadPicturesDto);
    
    // 确保不包含主键字段
    const { Id, ...dataWithoutId } = createUploadPicturesDto;
    console.log('处理后的数据:', dataWithoutId);
    
    const uploadPictures = this.uploadPicturesRepository.create(dataWithoutId);
    console.log('创建的实体:', uploadPictures);
    
    const result = await this.uploadPicturesRepository.save(uploadPictures);
    console.log('保存结果:', result);
    
    return Array.isArray(result) ? result[0] : result;
  }

  async findByServiceId(serviceId: string): Promise<UploadPictures[]> {
    console.log('=== UploadPicturesService 调试 ===');
    console.log('查询 serviceId:', serviceId);

    const result = await this.uploadPicturesRepository.find({
      where: { serviceId, deleted: false }, // 保持使用 boolean 类型
      order: { uploadTime: 'ASC' },
      select: [
        'Id',
        'serviceId',
        'name',
        'uploadTime',
        'imageUrl',
        'suffix',
        'deleted',
      ],
    });

    console.log('查询结果:', result);
    return result;
  }

  async softDeleteByServiceId(serviceId: string): Promise<void> {
    await this.uploadPicturesRepository.update(
      { serviceId },
      { deleted: true },
    );
  }

  async deleteByServiceId(serviceId: string): Promise<void> {
    await this.uploadPicturesRepository.delete({ serviceId });
  }
}